﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.ExtNet;
using Sharp.Portal.Mvc;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;
using PartialViewResult = Ext.Net.MVC.PartialViewResult;

// ReSharper disable Mvc.ViewNotResolved

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    [AutomaticTemplate]
    public class AvailablePermissionController : SharpController
    {
        // GET: Platform/AvailablePermission
        public ActionResult Index(string containerId)
        {
            return new PartialViewResult
            {
                Model = new AvailablePermissionIndexViewModel(),
                ContainerId = containerId,
                RenderMode = RenderMode.AddTo
            };
        }

        public async Task<StoreResult> GetTreeData(string node)
        {
            var leftTree = new Node()
            {
                Text = "根节点",
                NodeID = "Root",
                Expanded = true,
                Leaf = true,
                Checked = null
            };
            IEnumerable<PermissionDTO> list;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                list = await proxy.Channel.AllAvailablePermissions();
            }
            var builder = new TreeBuilder<Guid,PermissionDTO>
            {
                ChangeData = (p, treeNode) =>
                {
                    treeNode.Text = p.Title;
                    treeNode.NodeID = p.Id.ToString();
                    treeNode.AllowDrag = true;
                    treeNode.AllowDrop = true;
                    treeNode.AttributesObject = p;
                    treeNode.Leaf = list.All(x => x.ParentId != p.Id);
                    if (!treeNode.Leaf)
                        treeNode.Icon = Icon.Folder;
                    if (new[] { "02", "04", "08" }.Any(c => c == p.Category))
                        treeNode.Expanded = false;
                    else
                        treeNode.Expanded = true;
                }
            };

            builder.Build(list, leftTree, null);

            return this.Store(leftTree.Children, list.Count());
        }

        public ActionResult SaveToPermission(Guid[] ids)
        {
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                var res = proxy.Channel.AvailablePermissionToPermission(ids);

                return this.JsonNet(res);
            }

        }
    }
}